﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DeployJarUtil
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("deploy.xml");

            XmlNode name = doc.SelectSingleNode("service/name");
            txt_ServerName.Text = name.InnerText;

            XmlNode jarFilePath = doc.SelectSingleNode("service/jarFilePath");
            txt_JarPath.Text = jarFilePath.InnerText;

            XmlNode port = doc.SelectSingleNode("service/port");
            txt_Port.Text = port.InnerText;

            timer = new System.Windows.Forms.Timer();
            //1秒间隔
            timer.Interval = 1000;
            //执行事件
            timer.Tick += (s, e1) =>
            {
                RefreshStatus();
            };
            //开始执行
            timer.Start();
        }

        public void InitOpStatus()
        {
            btn_InstallService.Enabled = false;
            btn_StartService.Enabled = false;
            btn_UnstallService.Enabled = false;
            btn_StopService.Enabled = false;
            var serviceControllers = ServiceController.GetServices();
            bool existservice = false;
            foreach (var service in serviceControllers)
            {
                if (service.ServiceName == txt_ServerName.Text)
                {
                    existservice = true;
                    break;
                }
            }
            if (existservice)
            {
                var server = serviceControllers.FirstOrDefault(service => service.ServiceName == txt_ServerName.Text);
                if (server.Status == ServiceControllerStatus.Running)
                {
                    //服务运行中允许停止
                    btn_StopService.Enabled = true;
                }
                else
                {
                    //服务未运行允许卸载和启动
                    btn_UnstallService.Enabled = true;
                    btn_StartService.Enabled = true;
                }
            }
            else
            {
                //无此服务允许安装
                btn_InstallService.Enabled = true;
            }

        }

        delegate void RefreshStatusCallBack();

        private void RefreshStatus()
        {
            RefreshStatusCallBack d = new RefreshStatusCallBack(InitOpStatus);
            this.Invoke(d);
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_ServerName.Text))
            {
                MessageBox.Show("未填写服务名称");
                return;
            }
            if (string.IsNullOrEmpty(txt_JarPath.Text))
            {
                MessageBox.Show("未填选择jar包路径");
                return;
            }
            XmlDocument doc = new XmlDocument();
            doc.Load("deploy.xml");

            //id
            XmlNode id = doc.SelectSingleNode("service/id");
            id.InnerText = txt_ServerName.Text;
            //name
            XmlNode name = doc.SelectSingleNode("service/name");
            name.InnerText = txt_ServerName.Text;
            //description
            XmlNode description = doc.SelectSingleNode("service/description");
            description.InnerText = txt_ServerName.Text;
            //arguments
            string startCommand = startCommand = "-jar " + txt_JarPath.Text;
            if (!string.IsNullOrEmpty(txt_Port.Text))
            {
                startCommand += "  --server.port=" + txt_Port.Text;
            }
            XmlNode arguments = doc.SelectSingleNode("service/arguments");
            arguments.InnerText = startCommand;
            //jarFilePath
            XmlNode jarFilePath = doc.SelectSingleNode("service/jarFilePath");
            jarFilePath.InnerText = txt_JarPath.Text;
            //prot
            XmlNode port = doc.SelectSingleNode("service/port");
            port.InnerText = txt_Port.Text;
            //logpath
            XmlNode logpath = doc.SelectSingleNode("service/logpath");
            logpath.InnerText = AppDomain.CurrentDomain.BaseDirectory + "deploylog\\";

            doc.Save("deploy.xml");
            MessageBox.Show("保存成功");
        }

        private void btn_SelectJarPath_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择jar包";
            dialog.Filter = "jar文件(*.jar)|*.jar";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txt_JarPath.Text = dialog.FileName;
            }
            
        }

        private void btn_InstallService_Click(object sender, EventArgs e)
        {
            string command = "deploy.exe install";
            StartCmd(AppDomain.CurrentDomain.BaseDirectory, command, FinishCommand);
        }

        private void btn_UnstallService_Click(object sender, EventArgs e)
        {
            string command = "deploy.exe uninstall";
            StartCmd(AppDomain.CurrentDomain.BaseDirectory, command, FinishCommand);
        }

        private void btn_StartService_Click(object sender, EventArgs e)
        {
            string command = "deploy.exe start";
            StartCmd(AppDomain.CurrentDomain.BaseDirectory, command, FinishCommand);
            LogForm form = new LogForm();
            form.ShowDialog();
        }

        private void btn_StopService_Click(object sender, EventArgs e)
        {
            string command = "deploy.exe stop";
            StartCmd(AppDomain.CurrentDomain.BaseDirectory, command, FinishCommand);
        }

        public void StartCmd(String workingDirectory, String command, EventHandler FinsishEvent)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.EnableRaisingEvents = true;  // 启用Exited事件  
            p.Exited += FinsishEvent;   // 注册进程结束事件  
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.StandardInput.AutoFlush = true;
            string strOuput = p.StandardOutput.ReadToEnd();
            txt_Result.Text = strOuput;
            //等待程序执行完退出进程
            p.WaitForExit();
            p.Close();
        }

        public void FinishCommand(object sender, EventArgs e)
        {

        }


        System.Windows.Forms.Timer timer;

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer.Stop();
        }

    }
}
